package com.openthinks.joyniproject.utils.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 并发List. 该List可以实现读写互斥,保证数据唯一且线程安全
 * @since 
 *		v1.0
 * @version
 * 		v1.0, 2011-02-10 20:59:00
 * @author 
 *		Cloud
 *@param <E>
 * 			值
 */
public class ConcurrentList<E> {

	/**
	 * 读写锁
	 */
	private ReadWriteLock lock = new ReentrantReadWriteLock();
	
	/**
	 * 读锁
	 */
	private Lock readLock = lock.readLock();
	
	/**
	 * 写锁
	 */
	private Lock writeLock = lock.writeLock();
	
	/**
	 * 存储数据使用List
	 */
	private List<E> list = new ArrayList<E>();
	
	/**
	 * 存入数据
	 * @param bean
	 */
	public void add(E bean) {
		
		try {
			writeLock.lock();
			list.add(bean);
		} finally {
			writeLock.unlock();
		}	
	}
	
	/**
	 * 获取数据
	 * @param index
	 * 			位置(从0开始)
	 * @return
	 * 		数据
	 */
	public E get(int index) {
		
		try {
			readLock.lock();
			return list.get(index);
		} finally {
			readLock.unlock();
		}	
	}
	
	/**
	 * 删除数据
	 * @param index
	 * 			位置(从0开始)
	 * @return
	 * 			被删除的数据
	 */
	public E remove(int index) {
		
		try {
			writeLock.lock();
			return list.remove(index);
		} finally {
			writeLock.unlock();
		}
	}
	
	/**
	 * 清空数据
	 */
	public void clean() {
		
		try {
			writeLock.lock();
			list.clear();
		} finally {
			writeLock.unlock();
		}
	}
	
	/**
	 * 获取数量
	 * @return
	 */
	public int size() {
		
		try {
			readLock.lock();
			return list.size();
		} finally {
			readLock.unlock();
		}	
	}
}
